const incID = require("../functions/incID");
const Dramas = require("../models/Dramas")

const { addOneDrama, removeOneDrama, updateOneDrama, findDrama, findDramaByTag } = require("../services/dramaServices");

const addDrama = async (req, res) => {
    try {
        req.body.id_drama = await incID("drama");//调用incID实现剧本ID自增长
        const dramasaved = await addOneDrama(req.body);//调用addOneDrama添加数据
        return res.status(200).json({ success: dramasaved });
    }
    catch (err) {
        return res.status(400).json({ error_msg: err.message });
    }
}

const removeDrama = async (req, res) => {
    try {
        const dramaremoved = await removeOneDrama(req.body._id);//调用removeOneDrama查找_id并删除该数据
        if (dramaremoved == null) {
            return res.status(200).json({ error_msg: "未找到该条数据" });
        }
        else {
            return res.status(200).json({ success: dramaremoved });
        }
    }
    catch (err) {
        return res.status(400).json({ error_msg: err.message });
    }
}


const updateDrama = async (req, res) => {
    try {
        const dramaupdated = await updateOneDrama(req.body._id, req.body.column, req.body.content);

        if (dramaupdated == null) {
            return res.status(400).json({ error_msg: "未找到该条数据" });
        }
        else if (dramaupdated == 1) {
            return res.status(400).json({ error_msg: "字段错误" });
        }
        else if (dramaupdated == 2) {
            return res.status(400).json({ error_msg: "数据错误" });
        }
        else {
            return res.status(200).json({ success: dramaupdated });
        }
    }
    catch (err) {
        return res.status(400).json({ error_msg: err.message });
    }
}

// const getAllDrama = async (req, res) => {
//     try {
//         const dramafound = await Dramas.find()
//         return res.status(200).json({ success: dramafound });
//     }
//     catch (err) {
//         return res.status(400).json({ error_msg: err.message });
//     }
// }

const getDrama = async (req, res) => {
    try {
        const foundquery = req.query
        for (item in foundquery) {
            if (item == "_id") {
                foundquery[item] = foundquery[item]
            } else {
                foundquery[item] = eval("/" + foundquery[item] + "/")
            }
        }
        const dramafound = await Dramas.find(foundquery)
        if (!dramafound) {
            return res.status(200).json({ error_msg: "未找到" });
        }
        return res.status(200).json({ success: dramafound });
    }
    catch (err) {
        return res.status(400).json({ error_msg: err.message });
    }
}

// const getDramaByTag = async (req, res) => {
//     try {
//         const dramafound = await findDramaByTag(req.params.find)
//         return res.status(200).json({ success: dramafound });
//     }
//     catch (err) {
//         return res.status(400).json({ error_msg: err.message });
//     }
// }




module.exports = { addDrama, removeDrama, updateDrama, getDrama }